package com.yisu.expressway.main_page;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.Target;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.application.ExApplication;
import com.yisu.expressway.location.LocationService;
import com.yisu.expressway.main_page.HomePageActivity;
import com.yisu.expressway.model.AdItem;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.settings.AppConfig;
import com.yisu.expressway.settings.AppGlobalSetting;
import com.yisu.expressway.utils.BitmapUtil;
import com.yisu.expressway.utils.DisplayUtil;
import com.yisu.expressway.utils.FileUtil;
import com.yisu.expressway.utils.HBLog;
import com.yisu.expressway.utils.PhotoSaveUtil;
import com.yisu.expressway.utils.StringUtil;

import java.io.File;
import java.util.Map;

import butterknife.Bind;


public class SplashPageActivity extends BaseActivity {

    @Bind(R.id.iv_ad_img)
    protected ImageView mIv_Ad_img;

    private final static int WAITING_INTERVAL = 2000;
    //开机画面
    public final static String APP_START_IMAGE_REMOTE = "APP_START_IMAGE_REMOTE";
    public final static String LUBOBO_WELCOME_PICTURE_NAME = "lubobo_welcome_picture";

    AppGlobalSetting sp ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_page);

        sp = new AppGlobalSetting(this);
        initStartImage();
        getStartAdPage();
        getCurrentLocation();
        getSystemConfig();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                jump2RightPage();
            }
        }, WAITING_INTERVAL);
    }

    /**
     * 跳转至下一个合适页面 。
     */
    private void jump2RightPage(){
        startTargetActivity(HomePageActivity.class);
        finish();
    }

    private void initStartImage(){
        String localImage = getLocalWelcomePicturePath();

        if (null == localImage || "".equals(localImage)){
            return;
        }

        int width = DisplayUtil.getScreenWidth(this);
        int height = DisplayUtil.getScreenHeight(this);
        Bitmap bmp = BitmapUtil.getImage(localImage, width, height);
        if (null == bmp){
            return;
        }

        mIv_Ad_img.setImageBitmap(bmp);//new BitmapDrawable(bmp));
    }

    /**
     * 查询最新广告页图片
     */
    private void getStartAdPage(){
        ApiClientHelper.getApi(ApiSetting.getLoadPage(), new TypeToken<AdItem>() {
                },
                new Response.Listener<ApiResult<AdItem>>() {
                    @Override
                    public void onResponse(final ApiResult<AdItem> result) {
                        if (!result.success) {
                            return;
                        }

                        AdItem mAdImg = result.getResult();
                        if(mAdImg == null || StringUtil.isNullOrEmpty(mAdImg.imageUrl) ){
                            deleteStartImage();
                        }else{
                            downloadNewStartImage(mAdImg.imageUrl);
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                }, this);
    }

    /**
     * 获取位置信息
     */
    private void getCurrentLocation(){
        LocationService.getInstance().start();
    }

    private String getLocalWelcomePicturePath(){
        File folder = getStoragePath(this);
        String fileName = File.separator + LUBOBO_WELCOME_PICTURE_NAME + ".jpg";
        File file = new File(folder, fileName);
        if (!file.exists()) {
            return null;
        }
        return file.getAbsolutePath();
    }

    private void getSystemConfig(){
        ApiClientHelper.getApi(ApiSetting.getSystemConfig(), new TypeToken<Map<String,String>>() {
                },
                new Response.Listener<ApiResult<Map<String,String>>>() {
                    @Override
                    public void onResponse(final ApiResult<Map<String,String>> result) {
                        if (!result.success) {
                            return;
                        }

                        Map<String,String> systemMap = result.getResult();
                        sp.setStringGlobalItem(AppConfig.PREF_QINIU_UPLOAD_TOKEN,systemMap.get("Qi-Niu-Upload-Token"));
                        sp.setFloatGlobalItem(AppConfig.PREF_AUTO_ENTER_DISTANCE,Float.valueOf(systemMap.get("Current-Service-Area-Distance")));

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                }, this);
    }

    private File getStoragePath(Context context){

        String eStorageDir = Environment.getExternalStorageDirectory().toString() + File.separator + "yisu";

        File folder = new File(eStorageDir);
        if (!folder.exists()){
            folder.mkdir();
        }

        return folder;
    }

    private void downloadNewStartImage(final String imageUrl){

        if (null == imageUrl){
            return;
        }

        String remoteUrl = sp.getStringGlobalItem(APP_START_IMAGE_REMOTE,"");

        if (null != remoteUrl && remoteUrl.equals(imageUrl)){
            return;
        }

        String local2Delete = getLocalWelcomePicturePath();


        if (null != local2Delete){
            FileUtil.deleteIfExists(local2Delete);
        }

        //download
        new PhotoSaveUtil().setListener(new PhotoSaveUtil.OnPhotoSaveListener() {
            @Override
            public void onPhotoSaved(String localPath) {
                sp.setStringGlobalItem(APP_START_IMAGE_REMOTE,imageUrl);
            }
        }).save(getApplicationContext(), imageUrl, LUBOBO_WELCOME_PICTURE_NAME, false);

    }

    private void deleteStartImage(){
        sp.setStringGlobalItem(APP_START_IMAGE_REMOTE,"");
        String local2Delete = getLocalWelcomePicturePath();
        if (null != local2Delete){
            FileUtil.deleteIfExists(local2Delete);
        }
    }
}
